const { Sequelize } = require('sequelize');
const logger = require('../utils/logger');
const dotenv = require('dotenv');
const path = require('path');

// 加载环境变量
const envPath = path.resolve(__dirname, '../.env');
const result = dotenv.config({ path: envPath });

if (result.error) {
  logger.error('无法加载环境变量文件:', result.error);
  throw new Error('无法加载环境变量文件');
}

// 检查必要的环境变量
const requiredEnvVars = ['DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST'];
const missingEnvVars = requiredEnvVars.filter(varName => !process.env[varName]);

if (missingEnvVars.length > 0) {
  logger.error('缺少必要的环境变量:', missingEnvVars);
  throw new Error(`缺少必要的环境变量: ${missingEnvVars.join(', ')}`);
}

// 创建数据库连接实例
const createSequelizeInstance = () => {
  const config = {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT || 3306,
    dialect: 'mysql',
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    logging: process.env.NODE_ENV === 'development' 
      ? (msg) => logger.debug(msg)
      : false,
    timezone: '+08:00',
    define: {
      timestamps: true,
      underscored: true,
      charset: 'utf8mb4'
    },
    dialectOptions: {
      charset: 'utf8mb4',
      multipleStatements: true
    },
    pool: {
      max: parseInt(process.env.DB_POOL_MAX || '5'),
      min: parseInt(process.env.DB_POOL_MIN || '0'),
      acquire: parseInt(process.env.DB_POOL_ACQUIRE || '30000'),
      idle: parseInt(process.env.DB_POOL_IDLE || '10000')
    },
    retry: {
      max: 3,
      match: [
        /Deadlock/i,
        /SequelizeConnectionError/,
        /SequelizeConnectionRefusedError/,
        /SequelizeHostNotFoundError/,
        /SequelizeHostNotReachableError/,
        /SequelizeInvalidConnectionError/,
        /SequelizeConnectionTimedOutError/,
        /TimeoutError/
      ]
    }
  };

  logger.info('数据库配置:', {
    host: config.host,
    port: config.port,
    database: process.env.DB_NAME,
    user: process.env.DB_USER,
    pool: config.pool
  });

  return new Sequelize(
    process.env.DB_NAME,
    process.env.DB_USER,
    process.env.DB_PASSWORD,
    config
  );
};

// 创建数据库连接
const sequelize = createSequelizeInstance();

// 导出实例
module.exports = sequelize; 